mongoStore = require('../mongoStore')
errors = require('../errors')

gCollectionUser = ->
    db = yield mongoStore.gDatabase()
    db.collection 'user'

exports.gSignIn = (username, password)->
    user = yield from gCollectionUser()
    r = yield user.findOne({username})
    if r && r._id
        throw new errors.UserError('PasswordNotMatch') if r.password != password
        return r
    else
        throw new errors.UserError('UserNotExisted')

exports.gCreateUser = (body)->
    user = yield from gCollectionUser()
    r = yield user.insertOne(body)
    return r

exports.gAuthenticate = (userId)->
    _id = mongoStore.stringToObjectId(userId)

    user = yield from gCollectionUser()
    r = yield user.findOne({_id})
    return r